// pages/addAddress/addAddress.js

import QQMapWX from '../../lib/qqmap-wx-jssdk'
var qqmapsdk;
var qqmapsdk = new QQMapWX({
  key: '开发密钥（key）' // 必填
});
const db =  wx.cloud.database();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    defaultaddress:true,
    latitude: 0,
    longitude: 0,
    backfill: '',
    detailLocation: '',
    defaultAddress: false,
  },
  //数据回填方法
backfill: function (e) {
  var id = e.currentTarget.id;
  for (var i = 0; i < this.data.suggestion.length;i++){
    if(i == id){
      this.setData({
        backfill: this.data.suggestion[i].title,
        detailLocation: this.data.suggestion[i].addr,
        poi: {
          longitude: this.__data__.temLocList[i].location.lng,
          latitude: this.__data__.temLocList[i].location.lat,
          
        },
        suggestion: '',
      });

      // this.__data__.detailLocation = this.data.suggestion[i].address;
      // console.log(this);
      // console.log(this.__data__.detailLocation);
    }  
  }
  console.log("执行");
  // this.formSubmit();

},
getsuggest: function(e) {
  var _this = this;
  console.log(e);
  //调用关键词提示接口
  qqmapsdk.getSuggestion({
    //获取输入框值并设置keyword参数
    keyword: e.detail, //用户输入的关键词，可设置固定值,如keyword:'KFC'
    //region:'北京', //设置城市名，限制关键词所示的地域范围，非必填参数
    success: function(res) {//搜索成功后的回调
      console.log(res);
      _this.setData({
        temLocList: res.data,
      });
      var sug = [];
      for (var i = 0; i < res.data.length; i++) {
        sug.push({ // 获取返回结果，放到sug数组中
          title: res.data[i].title,
          id: res.data[i].id,
          addr: res.data[i].address,
          city: res.data[i].city,
          district: res.data[i].district,
          latitude: res.data[i].location.lat,
          longitude: res.data[i].location.lng
        });
      }
      _this.setData({ //设置suggestion属性，将关键词搜索结果以列表形式展示
        suggestion: sug
      });
    },
    fail: function(error) {
      console.error(error);
    },
    complete: function(res) {
      console.log(res);
    }
  });
},
  onChange() {
    console.log('change');
  },

  onAddressChange(e) {
    console.log(e);
    this.setData({
      door: e.detail.value
    });
  },

//重复了?
//   formSubmit(e) {
//     var _this = this;
//     //调用地址解析接口
//     console.log("formSubmit函数");
//     // console.log(this);
//     console.log(this.__data__.detailLocation);
//     qqmapsdk.geocoder({
//       //获取表单传入地址
//       address: this.__data__.detailLocation, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
//       success: function(res) {//成功后的回调
//         console.log(res);
//         var res = res.result;
//         var latitude = res.location.lat;
//         var longitude = res.location.lng;
//         //根据地址解析在地图上标记解析地址位置
//         _this.setData({ // 获取返回结果，放到markers及poi中，并在地图展示
//           markers: [{
//             id: 0,
//             title: res.title,
//             latitude: latitude,
//             longitude: longitude,
//             iconPath: './resources/placeholder.png',//图标路径
//             width: 20,
//             height: 20,
//             callout: { //可根据需求是否展示经纬度
//               content: latitude + ',' + longitude,
//               color: '#000',
//               display: 'ALWAYS'
//             }
//           }],
//           poi: { //根据自己data数据设置相应的地图中心坐标变量名称
//             latitude: latitude,
//             longitude: longitude
//           }
//         });
//         _this.setData({
// suggestion: '',
//       });
//       },
//       fail: function(error) {
//         console.error(error);
//       },
//       complete: function(res) {
//         console.log(res);
//       },

//     })
// },
  nearby_search:function(){
    var _this = this;
    // 调用接口
    let nowLocation = this.__data__.latitude + ',' + this.__data__.longitude;
    let keyword = this.__data__.backfill;
    

    qqmapsdk.search({
       keyword: keyword,  //搜索关键词
       location: nowLocation,  //设置周边搜索中心点
       success: function (res) { //搜索成功后的回调
        
         var mks = []
         for (var i = 0; i < res.data.length; i++) {
          //  console.log(123);
           mks.push({ // 获取返回结果，放到mks数组中
             title: res.data[i].title,
             id: res.data[i].id,
             latitude: res.data[i].location.lat,
             longitude: res.data[i].location.lng,
            //  iconPath: "/resources/my_marker.png", //图标路径
             width: 20,
             height: 20
           })
         }
        //  console.log(mks);   
         _this.setData({ //设置markers属性，将搜索结果显示在地图中
           markers: mks
         })

 
       },
       fail: function (res) {
         console.log(res);
       },
       complete: function (res){
         console.log(res);
       }
   });
 },
 setDefaultAddress() {
   console.log("执行");
this.setData({
  defaultAddress: true,
})
 },
  selectBuild(){
    wx.navigateTo({
      url: '../selectAddress/selectAddress'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    

    const {data} = options;
    console.log(data)
    this.setData({
      routerData: data,
    });
    var _this = this
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success (res) {
        console.log(res);
        console.log('纬度' + res.latitude)
        console.log('经度' + res.longitude)
        _this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        _this.setData({
          poi: {
            latitude: res.latitude,
            longitude: res.longitude
          }
        })
        console.log(_this.__data__.poi);
      },
      fail: (res) => console.log(res),
      complete: (res) => {
        // this.formSubmit();
      }
     })

    qqmapsdk = new QQMapWX({
      key: 'SIBBZ-SSJ6X-2ZL4D-TOOGT-CDXBK-LUBMK'
  });
  
  this.mapCtx = wx.createMapContext('mapId');
  this.mapCtx.on('markerClusterClick', res =>{
    console.log('markerClusterClick', res)
  })
  // this.formSubmit();
  },
  dataChange(e) {
    // console.log(e.detail);
    this.setData({
      myName: e.detail.value
    })
  },
  numberChange(e) {
    this.setData({
      myNumber: e.detail.value,
    })
  },
  submitLocation() {    
    this.setData({
      myLocation: this.__data__.backfill + this.__data__.Build + "栋" + this.__data__.door,
    })
    // console.log("zhixing1");
    let pages = getCurrentPages();
let prevPage = pages[pages.length - 2];
console.log(this.__data__.routerData);
if (this.__data__.routerData == "address") {
  const op = db.command
  let theLocation = {
    "myLocation": this.__data__.myLocation,
    "myName": this.__data__.myName,
    "myNumber": this.__data__.myNumber,
  }
  db.collection('userInfo').where({
    _openid: this.__data__.openid,
  }).update({
    data: {
      locationList: op.push(theLocation)
    },
    success: function(res) {
      console.log(res.data)
    },
    fail: (res) => {
      console.log(res);
    }
  })
  

  let locationList = prevPage.__data__.locationList;
  locationList.push({
    myLocation: this.__data__.backfill + this.__data__.Build + "栋" + this.__data__.door,
    myName: this.__data__.myName,
    myNumber: this.__data__.myNumber,
  })
        prevPage.setData({
      // myLocation:  this.__data__.backfill + this.__data__.Build + "栋" + this.__data__.door,
      // myName: this.__data__.myName,
      // myNumber:  this.__data__.myNumber,
      locationList: locationList
});
// orders.add({
//   data:{
//     locationList,
//   },
//   success:(res) => {
//     console.log(res);
//   }
// })
const _ = db.command;
db.collection("userInfo").where({
  openid: ""
}).update({
  // 我要摆烂！！(ಥ_ಥ)！！
  data: {
    // 表示指示数据库将字段自增 10
    progress: _.push(10)
  },
  success: function(res) {
    console.log(res.data)
  }
})

}
    if (this.__data__.routerData == "pakingLocation") {
      
      let pakingLocation = this.__data__.backfill + this.__data__.Build + "栋" + this.__data__.door
      // console.log(pakingLocation);
      prevPage.setData({
      pakingLocation: pakingLocation
})
// console.log(this.__data__.door);
    }else {
      console.log("zhixing2");
        prevPage.setData({
      getLocation: this.__data__.backfill + this.__data__.Build + "栋" + this.__data__.door})
    }
console.log(pages);
wx.navigateBack();
  },

  //逆地址解析
  formSubmit() {
    var _this = this;
    console.log(this.__data__.latitude);
    console.log(this.__data__.longitude);
    qqmapsdk.reverseGeocoder({
      //位置坐标，默认获取当前位置，非必须参数
      //  Object格式
        location: {
          latitude: this.__data__.latitude,
          longitude: this.__data__.longitude
        },

       //String格式
        // location: '39.984060,116.307520',
      // location: e.detail.value.reverseGeo || '', //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
      //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
      success: function(res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var mks = [];
        /**
         *  当get_poi为1时，检索当前位置或者location周边poi数据并在地图显示，可根据需求是否使用
         *
            for (var i = 0; i < result.pois.length; i++) {
            mks.push({ // 获取返回结果，放到mks数组中
                title: result.pois[i].title,
                id: result.pois[i].id,
                latitude: result.pois[i].location.lat,
                longitude: result.pois[i].location.lng,
                iconPath: './resources/placeholder.png', //图标路径
                width: 20,
                height: 20
            })
            }
        *
        **/
        //当get_poi为0时或者为不填默认值时，检索目标位置，按需使用
        mks.push({ // 获取返回结果，放到mks数组中
          title: res.address,
          id: 0,
          latitude: res.location.lat,
          longitude: res.location.lng,
          iconPath: './resources/placeholder.png',//图标路径
          width: 20,
          height: 20,
          callout: { //在markers上展示地址名称，根据需求是否需要
            content: res.address,
            color: '#000',
            display: 'ALWAYS'
          }
        });
        _this.setData({ //设置markers属性和地图位置poi，将结果在地图展示
          markers: mks,
          poi2: {
            latitude: res.location.lat,
            longitude: res.location.lng
          }
        });
        console.log("成功执行");
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {
        console.log(res);
      }
    })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    qqmapsdk.search({
      keyword: '酒店',
      success: function (res) {
          console.log(res);
      },
      fail: function (res) {
          console.log(res);
      },
  complete: function (res) {
      console.log(res);
  }
});
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})